# 把一个装有多个文件的文件夹切割为多个文件夹，文件平均分配
import tkinter as tk
import os
import math
from tkinter import ttk
from tkinter import messagebox
from tkinter import filedialog


def get_files_from_folder(folder_path: str) -> list[str]:
    files_list = []
    for item in os.listdir(folder_path):
        item_path = os.path.join(folder_path, item)
        if os.path.isfile(item_path):
            files_list.append(item)
    return files_list
    pass


def get_input(files_num: int) -> int:
    root = tk.Tk()
    root.geometry("300x300")
    root.attributes('-topmost', True)
    denominator = 1
    # 提示用户有多少个文件
    label_1 = tk.Label(root, text=f"你选择的文件夹里共有{files_num}个文件")
    label_1.place(relx=0, rely=0, relheight=0.4, relwidth=1)
    # 询问用户用户想分成几份
    label_2 = tk.Label(root, text="你想分成几份呢？")
    label_2.place(relx=0, rely=0.4, relheight=0.3, relwidth=1)
    # 用户输入
    user_input = tk.StringVar()
    entry = tk.Entry(root, textvariable=user_input)
    entry.place(relx=0, rely=0.7, relheight=0.2, relwidth=1)

    # 提交按钮

    def on_clicked():
        nonlocal denominator
        try:
            denominator = int(user_input.get())
            if denominator >= 2 and denominator <= files_num:
                root.destroy()
                # root.withdraw()
                # return denominator
            else:
                messagebox.showinfo(message=f"2<=份数<={files_num}")
                root.destroy()
                denominator = get_input(files_num)
        except Exception:
            messagebox.showinfo(message=f"2<=份数<={files_num}")
            root.destroy()
            denominator = get_input(files_num)

    btn = ttk.Button(root, text='提交', command=on_clicked)
    btn.place(relx=0, rely=0.9, relheight=0.1, relwidth=1)

    root.mainloop()

    return denominator


def create_n_folders(folder_path, denominator):
    folders_list = []
    for i in range(denominator):
        new_folder_path = folder_path + os.sep + str(i)
        os.makedirs(new_folder_path, exist_ok=True)
        folders_list.append(new_folder_path)
    return folders_list


def split_files_list(files_list, files_list_len, denominator):
    n_files_list: list[list] = []
    files_max_num_in_one_list = math.floor(files_list_len / denominator + 0.5)
    start_index = 0

    for i in range(denominator):
        end_index = (i + 1) * files_max_num_in_one_list
        if i != denominator - 1:
            n_files_list.append(files_list[start_index:end_index])
        else:
            n_files_list.append(files_list[start_index:])
        start_index = end_index
    return n_files_list


def move_files(folders_list, n_files_list, denominator, folder_path):
    for i in range(denominator):
        for file in n_files_list[i]:
            dst = folders_list[i] + os.sep + file
            source = folder_path + os.sep + file
            os.rename(source, dst)


if __name__ == '__main__':
    # 弹窗，用户选择文件夹
    parent_folder: str = filedialog.askdirectory(mustexist=True, title='选择文件夹')
    # 获取文件夹下的文件，不包括子文件夹内文件
    files_list: list[str] = get_files_from_folder(parent_folder)
    # 文件数量
    files_list_len = len(files_list)
    # 分割的份数N
    denominator: int = get_input(files_list_len)
    # 创建N个文件夹
    folders_list: list[str] = create_n_folders(parent_folder, denominator)
    # 把所有文件分为N组
    n_files_list: list[list] = split_files_list(
        files_list, files_list_len, denominator)
    # 把文件放入文件夹
    move_files(folders_list, n_files_list, denominator, parent_folder)
    # 结束
    messagebox.showinfo(message="分好了！")
